<template>
  <view class="container">
    <FilterNavbar>
      <template #center>
        <view class="navbar-title"> {{ pageTitle }} </view>
      </template>
    </FilterNavbar>
    <!-- <ve-alert> 创建保养仅作为信息的记录，不占用车辆库存，支持正常排车。 </ve-alert>
    <ve-gap size="24"></ve-gap> -->
    <ve-form v-if="form" ref="ve_form" :model="form" :rules="rules">
      <!-- 情况1：未带入车辆，需要手动选择 -->
      <ve-card title="车辆基本信息" type="none" fold v-model:initFold="foldStatus.fold1" v-if="pageFrom == 'indexTool'">
        <ve-form-item label="车牌号" :borderBottom="false" prop="licenseNo" required>
          <remote-select type="licenseNo" :label="form.licenseNo" @change="changeLicenseNo" v-model="form.carId" allowClear />
        </ve-form-item>
        <car-info-shadow v-if="carInfo.licenseNo" :info="carInfo" />
        <view :style="carInfo.licenseNo ? 'height: 24rpx;' : ''"></view>
      </ve-card>
      <!-- 情况2：带入保养id|车辆id|订单id，无需手动选择 -->
      <car-info :info="carInfo" v-else>
        <ve-cell label="保养单号" v-if="carInfo.maintenanceNo">{{ carInfo.maintenanceNo || '-' }}</ve-cell>
      </car-info>
      <ve-card title="保养信息" type="none" fold v-model:initFold="foldStatus.fold2" style="overflow: hidden">
        <ve-form-item label="保养单关联门店" prop="siteId" required>
          <remote-select type="site" v-model="form.siteId" v-model:label="form.siteName" :params="{ oldId: form.siteId }" allowClear />
        </ve-form-item>
        <ve-form-item label="修理厂" prop="maintenanceShopId">
          <remote-select
            :multiple="false"
            :type="remoteSelectData.attrs.type"
            v-model="form.maintenanceShopId"
            v-model:label="remoteSelectData.label"
            @change="changesupplierMainId"
            allowClear
            :params="{
              id: form.maintenanceShopId,
            }"
          ></remote-select>
        </ve-form-item>
        <ve-form-item label="本次保养里程" unit="公里">
          <ve-input-number v-model="form.entranceKilometre" placeholder="请输入" @blur="onBlurKilometre" />
        </ve-form-item>
        <ve-form-item label="保养间隔里程" unit="公里">
          <ve-input-number v-model="form.maintenanceLimitMileage" placeholder="请输入" @blur="onBlurKilometre" />
        </ve-form-item>
        <ve-form-item label="下次保养里程" unit="公里" prop="estimatedKilometre" required>
          <ve-input-number allowClear v-model="form.estimatedKilometre" placeholder="请输入" />
        </ve-form-item>
        <ve-form-item label="本次保养日期">
          <ve-date-picker v-model="form.entranceDate" mode="date" allowClear @change="setPlanTime"></ve-date-picker>
        </ve-form-item>
        <ve-form-item label="保养间隔时间" unit="天" prop="maintenanceLimitDay" labelTooltipContent>
          <template #content>
            <view>用于计算下次保养里程，下次保养里程</view>
            =本次保养里程+保养间隔里程。
          </template>
          <ve-input-number v-model="form.maintenanceLimitDay" placeholder="请输入" @change="setPlanTime" />
        </ve-form-item>
        <ve-form-item label="下次保养日期">
          <ve-date-picker v-model="form.estimatedTime" mode="date" allowClear></ve-date-picker>
        </ve-form-item>
        <ve-form-item label="承租人信息">
          <remote-select
            :disabled="byOrder"
            v-model="form.memberId"
            type="member_order_list"
            :params="{
              oldId: form.memberId,
              carId: form.carId,
              orderTypeList: [3], // 仅关联长租
            }"
            :label="memberLabel"
            allowClear
            @change="memberChange"
          ></remote-select>
        </ve-form-item>

        <ve-form-item label="关联订单号">
          <remote-select
            :disabled="byOrder"
            v-model="form.orderId"
            type="orderCar"
            :params="{
              oldOrderId: form.orderId,
              oldOrderType: form.orderType,
              carId: form.carId,
              memberId: form.memberId,
              orderTypeList: [3], // 仅关联长租
              useAuth: 1,
            }"
            :label="form.orderNo"
            allowClear
            @change="orderChange"
          />
        </ve-form-item>
        <ve-form-item label="负责人" prop="undertakerId">
          <remote-select
            type="staff_all_bysite"
            @change="changeUndertaker"
            :label="form.undertaker"
            v-model="form.undertakerId"
            :params="{ oldId: form.undertakerId, siteIdList: [carInfo.siteId] }"
            allowClear
          />
        </ve-form-item>

        <ve-form-item label="备注" labelPosition="top">
          <ve-input type="textarea" v-model="form.remark" placeholder="请输入" />
        </ve-form-item>

        <ve-form-item label="上传照片" :borderBottom="false" labelPosition="top" prop="fileIdList">
          <ve-upload v-model="form.fileIdList"></ve-upload>
        </ve-form-item>
      </ve-card>
      <ve-card title="保养费用" type="none" fold v-model:initFold="foldStatus.fold3">
        <ve-form-item label="保养费" unit="元">
          <template #label-extra>
            <ve-tag v-if="assetFeeInfo.feeStatus == 1" title="已付款无法编辑" color="orange" />
          </template>
          <ve-input-number
            v-model="form.maintenanceAmount"
            :precision="2"
            :min="0"
            :max="99999999.99"
            :disabled="assetFeeInfo.feeStatus == 1"
          />
        </ve-form-item>
        <ve-form-item label="费用备注" :borderBottom="false" labelPosition="top">
          <ve-input v-model="form.feeRemark" maxlength="200" type="textarea" />
        </ve-form-item>
      </ve-card>
    </ve-form>
    <ve-bottom-box size="mini">
      <ve-button type="primary" size="long" :loading="okLoading" @click="formSubmit">确认</ve-button>
    </ve-bottom-box>
  </view>
</template>

<script setup>
  import { onLoad } from '@dcloudio/uni-app'
  import { ref, computed, provide } from 'vue'
  import FilterNavbar from '@/components/FilterNavbar'
  import { getDetailApi, createApi, editApi } from '@/api/asset/car-maintenance'
  import { getCarDetail } from '@/api/asset/car-manager'
  import { orderCarInfo } from '@/api/asset/car-manager'
  import CarInfo from '@/pages/common/components/car-info.vue'
  import CarInfoShadow from '@/pages/common/components/car-info-shadow.vue'
  import useFormFold from '@/hooks/useFormFold'
  import { getWarnConfig } from '@/api/dict/operate'
  import dayjs from 'dayjs'
  import { findOrder } from '@/api/asset/car-violation'
  import { userStore } from '@/stores'
  import useToast from '@/hooks/useToast'

  const userInfoStore = userStore()

  // 修理厂
  const remoteSelectData = {
    prop: 'maintenanceShopId',
    label: '',
    type: 'remote-select',
    attrs: {
      type: 'supplierMain',
    },
  }
  const { foldStatus, foldValidate } = useFormFold([
    {
      key: 'fold1',
      props: ['licenseNo'],
    },
    {
      key: 'fold2',
      props: ['siteId', 'entranceDate', 'maintenanceShopId', 'exportKilometre', 'estimatedKilometre', 'undertakerId', 'fileIdList'],
    },
    {
      key: 'fold3',
    },
  ])
  const rules = ref({
    licenseNo: {
      required: true,
      message: '请选择车牌号',
    },
    siteId: {
      required: true,
      message: '请选择保养单关联门店',
    },
    estimatedKilometre: {
      required: true,
      message: '请输入下次保养里程',
    },
  })

  const onBlurKilometre = () => {
    if (!isNaN(form.value.maintenanceLimitMileage) && !isNaN(form.value.entranceKilometre)) {
      form.value.estimatedKilometre = form.value.maintenanceLimitMileage + form.value.entranceKilometre
    }
  }

  const setPlanTime = () => {
    if (form.value.entranceDate && form.value.maintenanceLimitDay != undefined) {
      form.value.estimatedTime = dayjs(form.value.entranceDate).add(form.value.maintenanceLimitDay, 'day').format('YYYY-MM-DD')
    }
  }

  const form = ref({
    carId: '',
  })
  provide('form', form.value)

  const record = ref({})
  const carInfo = ref({})
  const assetFeeInfo = ref({})
  const getDetail = async (id) => {
    const res = await getDetailApi({ id: id })
    form.value = Object.assign({}, res.result, {
      // 回填系统待办事项配置的保养间隔时间
      maintenanceLimitDay: form.value.maintenanceLimitDay,
      maintenanceLimitMileage: form.value.maintenanceLimitMileage,
    })
    carInfo.value = res.result
    form.value.entranceDate = res.result.entranceDate ?? undefined
    assetFeeInfo.value = res.result.assetFeeInfo || {}
    record.value = res.result
    remoteSelectData.label = res.result.maintenanceShop
  }
  const changesupplierMainId = (a, option = {}) => {
    form.value.maintenanceShopId = a
    form.value.maintenanceShop = option.supplierName
  }
  const changeUndertaker = (a, option = {}) => {
    form.value.undertakerId = a
    form.value.undertaker = option.realname
  }
  // 首页快捷跳转,获取车辆信息
  const getCarInfo = (carId) => {
    getCarDetail({ id: carId }).then((res) => {
      var car = res.result
      carInfo.value = res.result
      form.value.entranceKilometre = res.result.totalMileage //选车牌号自动带入本次保养里程
      form.value.carId = carId
      form.value.siteId = car.siteId
      form.value.siteName = car.siteName
      form.value.licenseNo = car.licenseNo
      record.value.licenseNo = car.licenseNo
      record.value.vin = car.vin
      record.value.modelName = car.modelName
      record.value.siteName = car.siteName
      record.value.libraryName = car.libraryName

      if (!form.value.undertakerId) {
        // 负责人默认登录人
        form.value.undertakerId = userInfoStore.staffInfo.staffId
        form.value.undertaker = userInfoStore.staffInfo.realname
      }
      // 如果存在本次保养里程，则默认下次保养里程为本次保养里程+保养间隔里程
      if (form.value.maintenanceLimitMileage && form.value.entranceKilometre) {
        form.value.estimatedKilometre = form.value.maintenanceLimitMileage + form.value.entranceKilometre
      }

      // 需要关联订单
      selectLinkedOrder()
    })
  }
  // 获取订单详情=>获取车信息和订单信息
  const getOrderCarInfo = (id, type) => {
    orderCarInfo({ id: id, type: type }).then((res) => {
      carInfo.value = res.result
      form.value.licenseNo = res.result.licenseNo
      form.value.carId = res.result.carId
      form.value.siteId = res.result.siteId
      form.value.siteName = res.result.siteName

      record.value.licenseNo = res.result.licenseNo
      record.value.vin = res.result.vin
      record.value.modelName = res.result.modelName
      record.value.siteName = res.result.siteName
      record.value.libraryName = res.result.libraryName
      record.value.orderNo = res.result.orderCode

      // 承租人信息
      form.value.memberId = res.result.memberId
      form.value.memberName = res.result.memberName
      form.value.memberPhone = res.result.memberPhone
      // 订单信息
      form.value.orderId = res.result.orderId
      form.value.orderNo = res.result.orderCode

      if (!form.value.undertakerId) {
        // 负责人默认登录人
        form.value.undertakerId = userInfoStore.staffInfo.staffId
        form.value.undertaker = userInfoStore.staffInfo.realname
      }
    })
  }

  const pageTitle = ref('新增保养')
  const byOrder = ref(false)
  const pageFrom = ref('')
  // 初始化表单和配置
  const initFormAndConfig = (options) => {
    const { id, orderId, carId, from } = options
    pageFrom.value = from
    getWarnConfig({ type: 1 }).then((res) => {
      form.value.maintenanceLimitDay = res.result.maintenanceLimitDay
      form.value.maintenanceLimitMileage = res.result.maintenanceLimitMileage
      // 编辑
      if (id) {
        pageTitle.value = '编辑保养'
        getDetail(id)
        return
      }
      // 从订单新增
      if (orderId) {
        byOrder.value = true
        pageTitle.value = '新增保养'
        getOrderCarInfo(form.value.orderId || orderId, 3)
        return
      }
      // 从车辆新增
      if (carId) {
        getCarInfo(carId)
        return
      }
      // 未带入任何信息 默认登录人
      form.value.undertakerId = userInfoStore.staffInfo.staffId
      form.value.undertaker = userInfoStore.staffInfo.realname
    })
  }
  onLoad(async (options) => {
    initFormAndConfig(options)
  })
  const toast = (text) => {
    uni.showToast({
      icon: 'none',
      title: text,
    })
  }

  // 承租人label
  const memberLabel = computed(() => {
    if (form.value.memberName || form.value.memberPhone) {
      return [form.value.memberName, form.value.memberPhone].join('|')
    } else {
      return ''
    }
  })

  // 承租人change
  const memberChange = (val, option) => {
    if (val) {
      form.value.memberId = val
      form.value.memberName = option.memberName
      form.value.memberPhone = option.phone

      // 需要获取最新的车牌号信息
      selectLinkedOrder()
    } else {
      form.value.memberId = undefined
      form.value.memberName = undefined
      form.value.memberPhone = undefined
    }
  }

  // 自动选中保养订单 默认选中第一个
  const selectLinkedOrder = () => {
    findOrder({
      carId: form.value.carId,
      memberId: form.value.memberId,
      orderTypeList: [3], // 仅长租
      useAuth: 1,
    }).then((res) => {
      if (res.code == 200) {
        const orderList = res.result
        if (orderList.length > 0) {
          // 当前存在已选择的订单时，判断是否需要清空
          let defaultSelectFirst = true
          if (form.value.orderId) {
            const hasSameOrderId = orderList.some((item) => item.orderId == form.value.orderId)
            if (hasSameOrderId) {
              // 存在相同订单，则不再默认选中第一个
              defaultSelectFirst = false
            }
          }
          if (defaultSelectFirst) {
            const order = orderList[0]
            form.value.orderId = order.orderId
            form.value.orderNo = order.orderNo

            form.value.memberId = order.memberId
            form.value.memberPhone = order.memberPhone
            form.value.memberName = order.memberName
          }
        } else {
          // 清空订单信息
          form.value.orderId = undefined
          form.value.orderNo = undefined
        }
      }
    })
  }
  // 自动选中保养订单 end
  // 订单change
  const orderChange = (val, option) => {
    if (val) {
      form.value.orderNo = option.orderNo
      form.value.orderType = option.orderType

      // 更新承租人信息
      form.value.memberId = option.memberId
      form.value.memberPhone = option.memberPhone
      form.value.memberName = option.memberName
    } else {
      form.value.orderNo = undefined
      form.value.orderType = undefined
    }
  }
  const okLoading = ref(false)
  const preSubmitFn = () => {
    return new Promise((resolve, reject) => {
      if (form.value.id) return resolve()
      let preSubmitInfo = undefined
      // 下次保养里程小于车辆上下次保养里程的情况
      if (form.value.estimatedKilometre < carInfo.value.estimatedKilometre) {
        preSubmitInfo = '新增保养的下次保养里程小于车辆上的下次保养里程，请确认是否新增？'
      }
      // 下次保养日期小于车辆上的情况
      if (dayjs(form.value.estimatedTime).isBefore(dayjs(carInfo.value.estimatedTime))) {
        preSubmitInfo = '新增保养的下次保养日期小于车辆上的下次保养日期，请确认是否新增？'
      }
      if (preSubmitInfo) {
        uni.showModal({
          title: '提示',
          cancelText: '取消',
          confirmText: '确认',
          content: preSubmitInfo,
          success: (res) => {
            if (res.confirm) {
              resolve()
            } else if (res.cancel) {
              reject()
            }
          },
        })
      } else {
        resolve()
      }
    })
  }

  const ve_form = ref(null)
  const formSubmit = () => {
    ve_form.value.validate(async (valid, errors) => {
      if (valid) {
        // 提交前置判断
        await preSubmitFn()
        okLoading.value = true
        let params = {
          ...form.value,
        }
        let fn = editApi
        if (!form.value.id) {
          // 新增
          params.status = 0
          fn = createApi
        }
        fn(params)
          .then((res) => {
            okLoading.value = false
            if (res.code == 200) {
              useToast({
                title: '操作成功',
              }).then(() => {
                // 车辆管理列表增加保养成功后，跳转至保养列表
                if (pageFrom.value == 'carManagerList') {
                  uni.redirectTo({
                    url: `/pages/asset/car-maintenance/list?id=${carInfo.value.id}`,
                  })
                }
                // 常用工具增加年检成功后，跳转至年检列表
                else if (pageFrom.value == 'indexTool') {
                  // 先跳转到车辆详情页
                  uni.redirectTo({
                    url: `/pages/asset/car-manager/detail/index?id=${carInfo.value.id}`,
                    success() {
                      // 再跳转到车辆详情>保养列表页
                      uni.navigateTo({
                        url: `/pages/asset/car-maintenance/list?id=${carInfo.value.id}`,
                      })
                    },
                  })
                } else {
                  uni.navigateBack()
                }
                // 触发事件，车辆编辑-保养新增成功
                uni.$emit('carEdit_maintenanceAddOk', params)
                // 刷新list
                uni.$emit('carMaintenance_getList')
              })
            } else {
              toast(res.message)
              return false
            }
          })
          .catch((_) => {
            okLoading.value = false
          })
      } else {
        foldValidate(errors)
        console.log('验证失败', errors)
      }
    })
  }

  // 选择车牌号
  const changeLicenseNo = (carId, option = {}) => {
    form.value.carId = carId
    form.value.licenseNo = option.licenseNo
    form.value.siteId = option.siteId
    form.value.siteName = option.siteName
    carInfo.value = option

    // 清空承租人信息和关联订单号信息
    form.value.memberId = undefined
    form.value.memberName = undefined
    form.value.memberPhone = undefined
    form.value.orderId = undefined
    form.value.orderNo = undefined
    form.value.orderType = undefined

    // 获取车辆违章以及关联订单信息
    if (carId) {
      selectLinkedOrder()
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    height: auto;
    padding: 24rpx 24rpx;
    background: #f7f8fa;
  }
</style>
